home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / deskbar-applet / handlers / mozilla.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-04-29  |  25.1 KB  |  793 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. import os
  5. import re
  6. import HTMLParser
  7. import base64
  8. import glob
  9. from os.path import join, expanduser, exists, basename
  10. from gettext import gettext as _
  11. from ConfigParser import RawConfigParser
  12. from xml.dom import minidom
  13. from deskbar.defs import VERSION
  14. import gtk
  15. from deskbar.Watcher import FileWatcher, DirWatcher
  16. import deskbar
  17. import deskbar.Indexer as deskbar
  18. import deskbar.Handler as deskbar
  19.  
  20. try:
  21.     set
  22. except NameError:
  23.     from sets import Set as set
  24.  
  25. from deskbar.BrowserMatch import is_preferred_browser
  26. from deskbar.BrowserMatch import BrowserSmartMatch, BrowserMatch
  27. USING_FIREFOX = False
  28. if is_preferred_browser('firefox'):
  29.     USING_FIREFOX = True
  30.  
  31.  
  32. def get_mozilla_home_file(needed_file):
  33.     default_profile_dir = expanduser('~/.mozilla/default')
  34.     if exists(default_profile_dir):
  35.         for d in os.listdir(default_profile_dir):
  36.             return join(default_profile_dir, d, needed_file)
  37.         
  38.     
  39.     return ''
  40.  
  41.  
  42. def get_firefox_home_file(needed_file):
  43.     firefox_dir = expanduser('~/.mozilla/firefox/')
  44.     config = RawConfigParser({
  45.         'Default': 0 })
  46.     config.read(expanduser(join(firefox_dir, 'profiles.ini')))
  47.     path = None
  48.     for section in config.sections():
  49.         if config.has_option(section, 'Default') and config.get(section, 'Default') == '1':
  50.             path = config.get(section, 'Path')
  51.             break
  52.             continue
  53.         if path == None and config.has_option(section, 'Path'):
  54.             path = config.get(section, 'Path')
  55.             continue
  56.     
  57.     if path == None:
  58.         return ''
  59.     
  60.     if path.startswith('/'):
  61.         return join(path, needed_file)
  62.     
  63.     return join(firefox_dir, path, needed_file)
  64.  
  65. GCONF_SHOW_ONLY_PRIMARY_KEY = deskbar.GCONF_DIR + '/mozilla/show_only_primary_search'
  66. SHOW_ONLY_PRIMARY = deskbar.GCONF_CLIENT.get_bool(GCONF_SHOW_ONLY_PRIMARY_KEY)
  67. if SHOW_ONLY_PRIMARY == None:
  68.     SHOW_ONLY_PRIMARY = False
  69.  
  70.  
  71. def _on_gconf_show_only_primary(value):
  72.     global SHOW_ONLY_PRIMARY
  73.     SHOW_ONLY_PRIMARY = value
  74.  
  75. deskbar.GCONF_CLIENT.notify_add(GCONF_SHOW_ONLY_PRIMARY_KEY, (lambda x, y, z, a: _on_gconf_show_only_primary(z.value.get_bool())))
  76. PRIMARY_SEARCH_ENGINE = None
  77.  
  78. try:
  79.     if USING_FIREFOX:
  80.         prefs_file = file(get_firefox_home_file('prefs.js'))
  81.     else:
  82.         prefs_file = None
  83.     for line in prefs_file:
  84.         if line.startswith('user_pref("browser.search.selectedEngine", "'):
  85.             line = line.strip()
  86.             PRIMARY_SEARCH_ENGINE = line[len('user_pref("browser.search.selectedEngine", "'):-len('");')]
  87.             break
  88.             continue
  89. except:
  90.     pass
  91.  
  92.  
  93. def _on_handler_preferences(dialog):
  94.     
  95.     def toggled_cb(sender, show_all_radio, show_primary_radio):
  96.         deskbar.GCONF_CLIENT.set_bool(GCONF_SHOW_ONLY_PRIMARY_KEY, show_primary_radio.get_active())
  97.  
  98.     
  99.     def sync_ui(new_show_only_primary, show_all_radio, show_primary_radio):
  100.         show_all_radio.set_active(not new_show_only_primary)
  101.         show_primary_radio.set_active(new_show_only_primary)
  102.  
  103.     glade = gtk.glade.XML(os.path.join(deskbar.SHARED_DATA_DIR, 'mozilla-search.glade'))
  104.     dialog = glade.get_widget('prefs-dialog')
  105.     show_all_radio = glade.get_widget('show_all_radio')
  106.     show_primary_radio = glade.get_widget('show_primary_radio')
  107.     show_primary_radio.set_active(SHOW_ONLY_PRIMARY)
  108.     show_all_radio.set_active(not SHOW_ONLY_PRIMARY)
  109.     show_all_radio.connect('toggled', toggled_cb, show_all_radio, show_primary_radio)
  110.     show_primary_radio.connect('toggled', toggled_cb, show_all_radio, show_primary_radio)
  111.     notify_id = None((None, deskbar.GCONF_CLIENT.notify_add, GCONF_SHOW_ONLY_PRIMARY_KEY), (lambda x, y, z, a: sync_ui(z.value.get_bool(), show_all_radio, show_primary_radio)))
  112.     dialog.set_icon_name('deskbar-applet')
  113.     dialog.show_all()
  114.     dialog.run()
  115.     dialog.destroy()
  116.     deskbar.GCONF_CLIENT.notify_remove(notify_id)
  117.  
  118.  
  119. def _check_requirements_bookmarks():
  120.     if is_preferred_browser('firefox') or is_preferred_browser('mozilla'):
  121.         return (deskbar.Handler.HANDLER_IS_HAPPY, None, None)
  122.     else:
  123.         return (deskbar.Handler.HANDLER_IS_NOT_APPLICABLE, 'Mozilla/Firefox is not your preferred browser, not using it.', None)
  124.  
  125.  
  126. def _check_requirements_search():
  127.     if is_preferred_browser('firefox'):
  128.         return (deskbar.Handler.HANDLER_IS_CONFIGURABLE, _('You can customize which search engines are offered.'), _on_handler_preferences)
  129.     elif is_preferred_browser('mozilla'):
  130.         return (deskbar.Handler.HANDLER_IS_HAPPY, None, None)
  131.     else:
  132.         return (deskbar.Handler.HANDLER_IS_NOT_APPLICABLE, 'Mozilla/Firefox is not your preferred browser, not using it.', None)
  133.  
  134. HANDLERS = {
  135.     'MozillaBookmarksHandler': {
  136.         'name': _('Web Bookmarks'),
  137.         'description': _('Open your web bookmarks by name'),
  138.         'requirements': _check_requirements_bookmarks,
  139.         'version': VERSION },
  140.     'MozillaSearchHandler': {
  141.         'name': _('Web Searches'),
  142.         'description': _("Search the web via your browser's search settings"),
  143.         'requirements': _check_requirements_search,
  144.         'version': VERSION },
  145.     'MozillaHistoryHandler': {
  146.         'name': _('Web History'),
  147.         'description': _('Open your web history by name'),
  148.         'requirements': _check_requirements_bookmarks,
  149.         'version': VERSION } }
  150.  
  151. class MozillaBookmarksHandler(deskbar.Handler.Handler):
  152.     
  153.     def __init__(self):
  154.         deskbar.Handler.Handler.__init__(self, 'stock_bookmark')
  155.         self._bookmarks = None
  156.  
  157.     
  158.     def initialize(self):
  159.         if not hasattr(self, 'watcher'):
  160.             self.watcher = FileWatcher()
  161.             self.watcher.connect(('changed',), (lambda watcher, f: self._parse_bookmarks()))
  162.         
  163.         parsed_file = self._parse_bookmarks()
  164.         if parsed_file != None:
  165.             self.watcher.add(parsed_file)
  166.         
  167.  
  168.     
  169.     def _parse_bookmarks(self):
  170.         (self._bookmarks, parsed_file, self._shortcuts_to_smart_bookmarks_map) = MozillaBookmarksParser(self).get_indexer()
  171.         return parsed_file
  172.  
  173.     
  174.     def stop(self):
  175.         self.watcher.remove_all()
  176.  
  177.     
  178.     def query(self, query):
  179.         x = self.query_smart_bookmarks(query, deskbar.DEFAULT_RESULTS_PER_HANDLER)
  180.         if x != None:
  181.             return x
  182.         else:
  183.             return self._bookmarks.look_up(query)[:deskbar.DEFAULT_RESULTS_PER_HANDLER]
  184.  
  185.     
  186.     def query_smart_bookmarks(self, query, max):
  187.         x = query.find(' ')
  188.         if x != -1:
  189.             prefix = query[:x]
  190.             
  191.             try:
  192.                 b = self._shortcuts_to_smart_bookmarks_map[prefix]
  193.                 text = query[x + 1:]
  194.                 return [
  195.                     BrowserSmartMatch(b.get_handler(), b.name, b.url, prefix, b, icon = b.icon)]
  196.             except KeyError:
  197.                 pass
  198.             except:
  199.                 None<EXCEPTION MATCH>KeyError
  200.             
  201.  
  202.         None<EXCEPTION MATCH>KeyError
  203.  
  204.  
  205.  
  206. class MozillaSearchHandler(deskbar.Handler.Handler):
  207.     
  208.     def __init__(self):
  209.         deskbar.Handler.Handler.__init__(self, 'stock_bookmark')
  210.         self._smart_bookmarks = None
  211.  
  212.     
  213.     def initialize(self):
  214.         smart_dirs = None
  215.         if USING_FIREFOX:
  216.             smart_dirs = [
  217.                 get_firefox_home_file('searchplugins'),
  218.                 get_firefox_home_file('search'),
  219.                 expanduser('~/.mozilla/searchplugins'),
  220.                 '/usr/lib/firefox/searchplugins',
  221.                 '/usr/local/lib/firefox/searchplugins',
  222.                 '/usr/lib/mozilla-firefox/searchplugins',
  223.                 '/usr/local/lib/mozilla-firefox/searchplugins']
  224.         else:
  225.             smart_dirs = [
  226.                 get_mozilla_home_file('search'),
  227.                 expanduser('~/.mozilla/searchplugins'),
  228.                 '/usr/lib/mozilla/searchplugins',
  229.                 '/usr/local/lib/mozilla/searchplugins']
  230.         if not hasattr(self, 'watcher'):
  231.             self.watcher = DirWatcher()
  232.             None((self.watcher.connect, 'changed'), (lambda watcher, f: self._parse_search_engines(smart_dirs)))
  233.         
  234.         self.watcher.add(smart_dirs)
  235.         self._parse_search_engines(smart_dirs)
  236.  
  237.     
  238.     def _parse_search_engines(self, smart_dirs):
  239.         self._smart_bookmarks = MozillaSmartBookmarksDirParser(self, smart_dirs).get_smart_bookmarks()
  240.  
  241.     
  242.     def stop(self):
  243.         self.watcher.remove_all()
  244.  
  245.     
  246.     def query(self, query):
  247.         if SHOW_ONLY_PRIMARY and PRIMARY_SEARCH_ENGINE != None:
  248.             for s in self._smart_bookmarks:
  249.                 if s.name == PRIMARY_SEARCH_ENGINE:
  250.                     return [
  251.                         s]
  252.                     continue
  253.             
  254.             return self._smart_bookmarks
  255.         else:
  256.             return self._smart_bookmarks
  257.  
  258.  
  259.  
  260. class MozillaBookmarksParser(HTMLParser.HTMLParser):
  261.     
  262.     def __init__(self, handler):
  263.         HTMLParser.HTMLParser.__init__(self)
  264.         self.handler = handler
  265.         self.chars = ''
  266.         self.href = None
  267.         self.icon_data = None
  268.         self.bookmarks = set()
  269.         self._shortcuts_to_smart_bookmarks_map = { }
  270.         self._indexer = deskbar.Indexer.Indexer()
  271.         
  272.         try:
  273.             if USING_FIREFOX:
  274.                 self.indexed_file = self._index_firefox()
  275.             else:
  276.                 self.indexed_file = self._index_mozilla()
  277.             self.close()
  278.         except Exception:
  279.             e = None
  280.             print 'Warning:Could not index Firefox bookmarks:', e
  281.  
  282.  
  283.     
  284.     def get_indexer(self):
  285.         '''
  286. \t\tReturns a completed indexer with the contents of bookmark file,
  287. \t\tthe name of the indexed file, and a map from shortcuts (or
  288. \t\tprefixes) to smart bookmarks - those bookmarks with %s in the
  289. \t\tURL.
  290. \t\t'''
  291.         return (self._indexer, self.indexed_file, self._shortcuts_to_smart_bookmarks_map)
  292.  
  293.     
  294.     def _index_mozilla(self):
  295.         
  296.         try:
  297.             bookmarks_file = get_mozilla_home_file('bookmarks.html')
  298.             if exists(bookmarks_file):
  299.                 self.feed(file(bookmarks_file).read())
  300.                 return bookmarks_file
  301.         except Exception:
  302.             msg = None
  303.             print 'Error retreiving Mozilla Bookmarks:', msg
  304.  
  305.  
  306.     
  307.     def _index_firefox(self):
  308.         
  309.         try:
  310.             bookmarks_file = get_firefox_home_file('bookmarks.html')
  311.             if exists(bookmarks_file):
  312.                 self.feed(file(bookmarks_file).read())
  313.                 return bookmarks_file
  314.         except Exception:
  315.             msg = None
  316.             print 'Error retreiving Mozilla Bookmarks:', msg
  317.  
  318.  
  319.     
  320.     def handle_starttag(self, tag, attrs):
  321.         tag = tag.lower()
  322.         if tag == 'a':
  323.             self.chars = ''
  324.             self.shortcuturl = None
  325.             for tag, value in attrs:
  326.                 if tag.lower() == 'href':
  327.                     self.href = value
  328.                 
  329.                 if tag.lower() == 'icon' and value != 'data:' and value.startswith('data:'):
  330.                     self.icon_data = value
  331.                 
  332.                 if tag.lower() == 'shortcuturl':
  333.                     self.shortcuturl = value
  334.                     continue
  335.             
  336.         
  337.  
  338.     
  339.     def handle_endtag(self, tag):
  340.         tag = tag.lower()
  341.         if tag == 'a':
  342.             if self.href == None or self.href.startswith('javascript:'):
  343.                 return None
  344.             
  345.             pixbuf = None
  346.             if self.icon_data != None:
  347.                 
  348.                 try:
  349.                     (header, content) = self.icon_data.split(',', 2)
  350.                     loader = gtk.gdk.PixbufLoader()
  351.                     loader.set_size(deskbar.ICON_HEIGHT, deskbar.ICON_HEIGHT)
  352.                     
  353.                     try:
  354.                         loader.write(base64.b64decode(content))
  355.                     except AttributeError:
  356.                         loader.write(base64.decodestring(content))
  357.  
  358.                     loader.close()
  359.                     pixbuf = loader.get_pixbuf()
  360.                 except Exception:
  361.                     msg = None
  362.                     print 'Error:mozilla.py:handle_endtag:', msg
  363.  
  364.                 self.icon_data = None
  365.             
  366.             bookmark = BrowserMatch(self.handler, self.chars, self.href, icon = pixbuf)
  367.             if self.shortcuturl != None:
  368.                 bookmark = BrowserSmartMatch(self.handler, self.chars, self.href, self.shortcuturl, bookmark, icon = pixbuf)
  369.                 self._shortcuts_to_smart_bookmarks_map[self.shortcuturl] = bookmark
  370.             else:
  371.                 self._indexer.add('%s %s' % (self.chars, self.href), bookmark)
  372.         
  373.  
  374.     
  375.     def handle_data(self, chars):
  376.         self.chars = self.chars + chars
  377.  
  378.  
  379.  
  380. class Firefox2SearchEngineParser:
  381.     
  382.     def __init__(self, filename):
  383.         self.filename = filename
  384.         self._infos = {
  385.             'name': '',
  386.             'action': '',
  387.             'description': '',
  388.             'url': '' }
  389.         self._namespace = None
  390.  
  391.     
  392.     def get_infos(self):
  393.         return self._infos
  394.  
  395.     
  396.     def parse(self):
  397.         xml = minidom.parse(self.filename)
  398.         self._detect_namespace(xml)
  399.         self._parse_name(xml)
  400.         self._parse_description(xml)
  401.         self._parse_action_and_url(xml)
  402.         
  403.         try:
  404.             self._parse_image(xml)
  405.         except Exception:
  406.             msg = None
  407.             print 'Error parsing icon for %s\n%s' % (self.filename, msg)
  408.  
  409.  
  410.     
  411.     def _detect_namespace(self, xml):
  412.         
  413.         try:
  414.             plugin = xml.getElementsByTagName('SearchPlugin')[0]
  415.             ns = plugin.getAttribute('xmlns:os')
  416.             if ns == '':
  417.                 return None
  418.             
  419.             self._namespace = 'os'
  420.         except:
  421.             pass
  422.  
  423.  
  424.     
  425.     def _ns_convert(self, tagname):
  426.         if self._namespace is not None:
  427.             return self._namespace + ':' + tagname
  428.         else:
  429.             return tagname
  430.  
  431.     
  432.     def _parse_name(self, xml):
  433.         for node in xml.getElementsByTagName(self._ns_convert('ShortName'))[0].childNodes:
  434.             self._infos['name'] += node.data
  435.         
  436.  
  437.     
  438.     def _parse_description(self, xml):
  439.         for node in xml.getElementsByTagName(self._ns_convert('Description'))[0].childNodes:
  440.             self._infos['description'] += node.data
  441.         
  442.  
  443.     
  444.     def _parse_action_and_url(self, xml):
  445.         url_node = None
  446.         for node in xml.getElementsByTagName(self._ns_convert('Url')):
  447.             if node.getAttribute('type') == 'text/html':
  448.                 url_node = node
  449.                 break
  450.                 continue
  451.         
  452.         if url_node is None:
  453.             raise ParseException('No Url tag of type text/html in %s' % self.filename)
  454.         
  455.         self._infos['url'] = url_node.getAttribute('template')
  456.         self._infos['action'] = self._infos['url']
  457.         params = ''
  458.         for param in url_node.getElementsByTagName(self._ns_convert('Param')):
  459.             key = param.getAttribute('name')
  460.             value = param.getAttribute('value')
  461.             params += '&%s=%s' % (key, value)
  462.         
  463.         params = params[1:]
  464.         if params != '':
  465.             self._infos['action'] += '?' + params
  466.         
  467.         self._infos['action'] = self._infos['action'].replace('{searchTerms}', '%s')
  468.         self._infos['action'] = self._infos['action'].replace('{SearchTerms}', '%s')
  469.  
  470.     
  471.     def _parse_image(self, xml):
  472.         
  473.         try:
  474.             img_tag = xml.getElementsByTagName(self._ns_convert('Image'))[0]
  475.         except:
  476.             return None
  477.  
  478.         loader = gtk.gdk.PixbufLoader()
  479.         loader.set_size(deskbar.ICON_HEIGHT, deskbar.ICON_HEIGHT)
  480.         content = ''
  481.         for data in img_tag.childNodes:
  482.             content += data.data
  483.         
  484.         header = 'data:image/x-icon;base64,'
  485.         content = content[content.index(header) + len(header):]
  486.         
  487.         try:
  488.             loader.write(base64.b64decode(content))
  489.         except AttributeError:
  490.             loader.write(base64.decodestring(content))
  491.  
  492.         loader.close()
  493.         pixbuf = loader.get_pixbuf()
  494.         self._infos['pixbuf'] = pixbuf
  495.  
  496.  
  497.  
  498. class MozillaSmartBookmarksParser:
  499.     
  500.     def __init__(self, f):
  501.         '''
  502. \t\tInit the parse, no exception here
  503. \t\t'''
  504.         self.f = f
  505.         self.infos = {
  506.             'search': { },
  507.             'input': { } }
  508.  
  509.     
  510.     def get_infos(self):
  511.         infos = { }
  512.         args = '?'
  513.         for key, arg in self.infos['input'].items():
  514.             args += '%s=%s&' % (key, arg)
  515.         
  516.         if args.endswith('&'):
  517.             args = args[:-1]
  518.         
  519.         infos['name'] = self.infos['search']['name']
  520.         infos['description'] = self.infos['search']['description']
  521.         if 'url' not in self.infos['search']:
  522.             infos['url'] = self.infos['search']['action']
  523.         else:
  524.             infos['url'] = self.infos['search']['url']
  525.         infos['action'] = self.infos['search']['action'] + args
  526.         img = self._find_icon()
  527.         if img is not None:
  528.             infos['icon'] = img
  529.         
  530.         return infos
  531.  
  532.     
  533.     def parse(self):
  534.         '''
  535. \t\t'''
  536.         tokenizer = Tokenizer(self.f)
  537.         n = None
  538.         state = None
  539.         tokens = [
  540.             tokenizer.get_next_token(),
  541.             tokenizer.get_next_token()]
  542.         while tokens[0] != None:
  543.             (state, n, rest) = self._handle_token(state, tokens)
  544.             if n == None:
  545.                 break
  546.             
  547.             tokens = rest
  548.             for i in range(n - len(rest)):
  549.                 tokens.append(tokenizer.get_next_token())
  550.             
  551.  
  552.     
  553.     def _find_icon(self):
  554.         
  555.         try:
  556.             parent_dir = self.f[:self.f.rindex('/')]
  557.             return _[1][0]
  558.         except Exception:
  559.             msg = None
  560.             print 'WARNING: Error detecting icon for smart bookmark:%s\n%s' % (self.f, msg)
  561.             return None
  562.  
  563.  
  564.     
  565.     def _handle_token(self, state, tokens):
  566.         if state == None:
  567.             if tokens == [
  568.                 '<',
  569.                 'search'] or tokens == [
  570.                 '<',
  571.                 'SEARCH']:
  572.                 return ('search', 3, [])
  573.             elif state == None:
  574.                 raise ParseException('File %s does not begin with <search' % self.f)
  575.             
  576.         if state == 'search' and tokens[1] == '=':
  577.             self.infos['search'][tokens[0]] = tokens[2]
  578.             return ('search', 3, [])
  579.         
  580.         if (state == 'search' or state == 'anotherinput') and tokens == [
  581.             '>',
  582.             '<',
  583.             'input']:
  584.             return ('input', 6, [])
  585.         elif state == 'search':
  586.             raise ParseException('Expecting <input after <search section in file %s' % self.f)
  587.         
  588.         if state == 'input' and tokens[1] == '=':
  589.             if tokens[3] == 'user':
  590.                 self.infos['input'][tokens[2]] = '%s'
  591.                 if tokens[4] != '=':
  592.                     return ('anotherinput', 3, tokens[4:])
  593.                 
  594.             else:
  595.                 self.infos['input'][tokens[2]] = tokens[5]
  596.             return ('anotherinput', 3, [])
  597.         
  598.         return (None, None, None)
  599.  
  600.  
  601.  
  602. class TokenException(Exception):
  603.     
  604.     def __init__(self, msg):
  605.         Exception.__init__(self, msg)
  606.  
  607.  
  608.  
  609. class ParseException(Exception):
  610.     
  611.     def __init__(self, msg):
  612.         Exception.__init__(self, msg)
  613.  
  614.  
  615.  
  616. class Tokenizer:
  617.     
  618.     def __init__(self, f):
  619.         '''
  620. \t\tInit the tokenizer on the given file, may throw an exception.
  621. \t\t'''
  622.         self.i = 0
  623.         self.f = f
  624.         self.data = file(f).read()
  625.         self.state = 'linestart'
  626.  
  627.     
  628.     def get_next_token(self):
  629.         '''
  630. \t\tReturns the next token in the file.
  631. \t\tA token is one of:
  632. \t\t< = > name
  633. \t\t
  634. \t\tReturns None when the end of file is reached and beyond
  635. \t\t'''
  636.         while self.i < len(self.data):
  637.             char = self.data[self.i]
  638.             if char.isspace() and not (char == '\n'):
  639.                 self.i += 1
  640.                 continue
  641.             
  642.             if self.state == 'linestart' and char == '#':
  643.                 while self.i < len(self.data) and self.data[self.i] != '\n':
  644.                     self.i += 1
  645.                     continue
  646.                     self
  647.                 self.i += 1
  648.                 continue
  649.             
  650.             next_token = self.read_token()
  651.             if next_token == '\n':
  652.                 self.state = 'linestart'
  653.                 continue
  654.             
  655.             return next_token
  656.  
  657.     
  658.     def read_token(self):
  659.         '''
  660. \t\tReturn the token, self.i must point to the first char in this token.
  661. \t\tself.i is updated to point just after the returned token
  662. \t\tReturned token is one of:
  663. \t\t< = > 
  664.  name
  665. \t\t'''
  666.         char = self.data[self.i]
  667.         if char == '<' and char == '=' and char == '>' or char == '\n':
  668.             self.i += 1
  669.             return char
  670.         elif char == '"':
  671.             closing = self.data[self.i + 1:].find('"')
  672.             if closing == -1:
  673.                 raise TokenException("Couldn't find a proper closing quote in %s" % self.f)
  674.             
  675.             token = self.data[self.i + 1:self.i + 1 + closing]
  676.             self.i += closing + 2
  677.             return token
  678.         else:
  679.             token = ''
  680.             while self.i < len(self.data) and not self.data[self.i].isspace() and self.data[self.i] not in '=><':
  681.                 token += self.data[self.i]
  682.                 self.i += 1
  683.                 continue
  684.                 self
  685.             return token
  686.  
  687.  
  688.  
  689. class MozillaSmartBookmarksDirParser:
  690.     
  691.     def __init__(self, handler, dirs):
  692.         self._smart_bookmarks = []
  693.         bookmark_names = []
  694.         found_bookmarks = []
  695.         for bookmarks_dir in dirs:
  696.             if not exists(bookmarks_dir):
  697.                 continue
  698.             
  699.             for f in glob.glob(join(bookmarks_dir, '*.src')):
  700.                 bmname = basename(f)
  701.                 if bmname in bookmark_names:
  702.                     continue
  703.                     continue
  704.                 found_bookmarks.append(f)
  705.             
  706.             for f in glob.glob(join(bookmarks_dir, '*.xml')):
  707.                 bmname = basename(f)
  708.                 if bmname in bookmark_names:
  709.                     continue
  710.                     continue
  711.                 found_bookmarks.append(f)
  712.             
  713.         
  714.         for f in found_bookmarks:
  715.             img = None
  716.             if f.endswith('.xml'):
  717.                 parser = Firefox2SearchEngineParser(f)
  718.             else:
  719.                 parser = MozillaSmartBookmarksParser(f)
  720.             
  721.             try:
  722.                 parser.parse()
  723.                 infos = parser.get_infos()
  724.                 if infos.has_key('pixbuf'):
  725.                     bookmark = BrowserMatch(handler, infos['name'], infos['url'], pixbuf = infos['pixbuf'])
  726.                     bookmark = BrowserSmartMatch(handler, infos['name'], infos['action'], pixbuf = infos['pixbuf'], bookmark = bookmark)
  727.                 elif infos.has_key('icon'):
  728.                     bookmark = BrowserMatch(handler, infos['name'], infos['url'], icon = infos['icon'])
  729.                     bookmark = BrowserSmartMatch(handler, infos['name'], infos['action'], icon = infos['icon'], bookmark = bookmark)
  730.                 else:
  731.                     bookmark = BrowserMatch(handler, infos['name'], infos['url'])
  732.                     bookmark = BrowserSmartMatch(handler, infos['name'], infos['action'], bookmark = bookmark)
  733.                 self._smart_bookmarks.append(bookmark)
  734.             continue
  735.             except Exception:
  736.                 msg = None
  737.                 print 'Error:MozillaSmartBookmarksDirParser:cannot parse smart bookmark: %s\n%s' % (f, msg)
  738.                 continue
  739.             
  740.  
  741.         
  742.  
  743.     
  744.     def get_smart_bookmarks(self):
  745.         '''
  746. \t\tReturn a list of MozillaSmartMatch instances representing smart bookmarks
  747. \t\t'''
  748.         return self._smart_bookmarks
  749.  
  750.  
  751. MOZILLA_HISTORY_REGEX = re.compile('\\=http[0-9a-zA-Z\\-\\&\\%\\=\\?\\:\\/\\.]*\\)')
  752.  
  753. class MozillaHistoryHandler(deskbar.Handler.Handler):
  754.     
  755.     def __init__(self):
  756.         deskbar.Handler.Handler.__init__(self, 'epiphany-history.png')
  757.         self._history = None
  758.  
  759.     
  760.     def initialize(self):
  761.         self._indexer = deskbar.Indexer.Indexer()
  762.         self._history = self._parse_history()
  763.         for history_url in self._history:
  764.             history_wo_http = history_url[history_url.find('//') + 2:]
  765.             if history_wo_http.find('www.') == -1:
  766.                 history_wo_www = history_wo_http
  767.             else:
  768.                 history_wo_www = history_wo_http[history_wo_http.find('www.') + 4:]
  769.             self._indexer.add('%s %s %s' % (history_wo_www, history_wo_http, history_url), BrowserMatch(self, history_wo_www, history_url, True))
  770.         
  771.  
  772.     
  773.     def _parse_history(self):
  774.         if USING_FIREFOX:
  775.             historydat = get_firefox_home_file('history.dat')
  776.         else:
  777.             historydat = get_mozilla_home_file('history.dat')
  778.         
  779.         try:
  780.             historycontents = file(historydat).read()
  781.             historycontents = re.findall(MOZILLA_HISTORY_REGEX, historycontents)
  782.             historycontents = [ x[1:-1] for x in historycontents ]
  783.             return historycontents
  784.         except:
  785.             return ''
  786.  
  787.  
  788.     
  789.     def query(self, query):
  790.         return self._indexer.look_up(query)[:deskbar.DEFAULT_RESULTS_PER_HANDLER]
  791.  
  792.  
  793.